﻿using System;
using System.IO.Ports;
using System.Threading;

namespace Device.Base.Comm
{
    /// <summary>
    /// 串口帮助类
    /// </summary>
    public class SerialPortHelper : ITransmission, IDisposable
    {
        #region 事件和字段属性定义

        // public CommParameter Parameter { get; set; }
        public event Action<byte[]> Received;
        public SerialPort SerialPort;
        public bool ReceiveEventFlag = false;  //接收事件是否有效 false表示有效



        #endregion

        /// <summary>
        /// 构造函数
        /// </summary>
        public SerialPortHelper() : this("COM1", 9600, Parity.None, 8, StopBits.One)
        {
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="portName">端口</param>
        /// <param name="baudRate">波特率</param>
        /// <param name="parity">校验位</param>
        /// <param name="dataBits">数据位</param>
        /// <param name="stopBits">停止位</param>
        public SerialPortHelper(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
        {


            try
            {
                //串口配置
                SerialPort = new SerialPort
                {

                    BaudRate = baudRate,
                    Parity = parity,
                    DataBits = dataBits,
                    StopBits = stopBits
                };
                SerialPort.PortName = portName;
                //SerialPort.Handshake = Handshake.None;
                //SerialPort.RtsEnable = true;
                //SerialPort.ReadTimeout = 2000;

            }
            catch (Exception)
            {
                // ignored
            }


        }
        #region 串口操作集合
        /// <summary>
        /// 释放串口资源
        /// </summary>
        // ~SerialPortHelper()

        public void Dispose()
        {
            Close();
        }

        /// <summary>
        /// 打开串口
        /// </summary>
        public bool Open()
        {
            if (!SerialPort.IsOpen)
            {
                try
                {
                    SerialPort.Open();
                    SerialPort.DataReceived += DataReceived;
                    return true;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            return false;
        }
        /// <summary>
        /// 关闭串口
        /// </summary>
        public bool Close()
        {
            if (SerialPort.IsOpen)
            {
                //SerialPort.re DataReceived
                SerialPort.DataReceived -= DataReceived;
                SerialPort.Close();
                return true;
            }
            return false;
        }
        /// <summary>
        /// 串口是否打开
        /// </summary>
        /// <returns></returns>
        public bool IsOpen()
        {
            return SerialPort.IsOpen;
        }
        public bool Send(byte[] buffer)
        {
            //禁止接收事件时直接退出
            if (ReceiveEventFlag)
            {
                return false;
            }
            if (SerialPort.IsOpen)
            {
                SerialPort.Write(buffer, 0, buffer.Length);
                return true;
            }
            return false;
        }


        /// <summary>
        /// 数据接收
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //禁止接收事件时直接退出
            if (ReceiveEventFlag)
            {
                return;
            }
            Thread.Sleep(50);
            if (SerialPort.IsOpen)
            {
                byte[] data = new byte[SerialPort.BytesToRead];
                SerialPort.Read(data, 0, data.Length);
                Received?.Invoke(data); 
            }
        }
         

        #endregion
    }

}
